package com.zmc.order.infrastructure.updater.order;

import com.zmc.common.constant.QueueConstant;
import com.zmc.common.exception.base.BusinessException;
import com.zmc.order.infrastructure.bean.vo.OrderReturnApplyVo;
import com.zmc.order.infrastructure.entity.MerchantOrderEntity;
import com.zmc.order.infrastructure.entity.OrderReturnApplyEntity;
import com.zmc.order.infrastructure.enums.OrderEnum;
import com.zmc.order.infrastructure.service.MerchantOrderService;
import com.zmc.order.infrastructure.service.OrderReturnApplyService;
import com.zmc.order.infrastructure.service.OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;

/**
 * @Author：zmc
 * @Date：2025/5/15 18:13
 * 订单审批退款
 */
@Component
public class OrderRefundApproveUpdater<T> implements OderUpdater<T> {

    public static Logger log = LoggerFactory.getLogger(OrderRefundApproveUpdater.class);

    @Autowired
    private OrderService orderService;

    @Autowired
    private MerchantOrderService merchantOrderService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private OrderReturnApplyService orderReturnApplyService;


    @Override
    @Transactional
    public void execute(T param) {
        OrderReturnApplyVo vo = (OrderReturnApplyVo) param;
        MerchantOrderEntity merchantOrder = merchantOrderService.getByOrderSn(vo.getOrderSn());
        if (merchantOrder == null) {
            throw new BusinessException("订单已不存在");
        }
        if (merchantOrder.getStatus() == OrderEnum.ORDER_STATUS_REFUNDING.getCode()) {
            log.error("当前订单：orderSn:{},正在退款中", merchantOrder.getOrderSn());
            throw new BusinessException("正在退款中");
        } else if (merchantOrder.getStatus() == OrderEnum.ORDER_STATUS_REFUNDED.getCode()) {
            log.error("当前订单：orderSn:{},已完成退款", merchantOrder.getOrderSn());
            throw new BusinessException("订单已完成退款");
        } else if (merchantOrder.getStatus() == OrderEnum.ORDER_STATUS_HAS_SEND_GOOD.getCode() ||
                merchantOrder.getStatus() == OrderEnum.ORDER_STATUS_COMPLETE.getCode()) {
            //检查退款申请单
            OrderReturnApplyEntity returnApplyEntity = orderReturnApplyService.getByOrderSn(vo.getOrderSn());
            if (returnApplyEntity == null) {
                throw new BusinessException("退款申请单不存在");
            }
            //审批通过，退款
            if ("success".equals(vo.getResult())) {
                returnApplyEntity.setStatus(OrderEnum.ORDER_REFUND_PROCESSING.getCode());
            } else {
                //审批拒绝
                returnApplyEntity.setStatus(OrderEnum.ORDER_REFUND_REJECT.getCode());
                //更新商户订单
                merchantOrderService.updateStatus(vo.getOrderSn(), OrderEnum.ORDER_STATUS_CLOSE.getCode());
                //更新用户订单
                orderService.updateStatus(merchantOrder.getUserOrderSn(), OrderEnum.ORDER_STATUS_CLOSE.getCode());
            }
            orderReturnApplyService.updateById(returnApplyEntity);
        } else {
            log.error("当前订单：orderSn:{}, status: {}, 不能退款", merchantOrder.getOrderSn(), merchantOrder.getStatus());
            throw new BusinessException("当前订单状态不能退款");
        }
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
            @Override
            public void afterCommit() {
                //审核成功，立即退款
                if ("success".equals(vo.getResult())) {
                    rabbitTemplate.convertAndSend(QueueConstant.REFUND_EXCHANGE, QueueConstant.REFUND_ROUTING_KEY, merchantOrder.getUserOrderSn());
                }

            }
        });
    }
}
